const dataBase = require('../dataBase')
const jsonwebtoken = require('jsonwebtoken')
const config = require('../JWT_Config')

// 注册新用户
function registerNewUser(req, res){
    const myNewInfo = req.body

    // 检查是否信息填写完整
    if (myNewInfo.phoneNumber === '' || myNewInfo.password === '' || myNewInfo.newPassword ===
        '' || myNewInfo.nickname === '' || myNewInfo.sex === '' || myNewInfo.university === '') {
        return res.ErrorFun('请将信息填写完整再进行注册!')
    }
    
    // 判断QQ邮箱验证码是否填写
    if(myNewInfo.myVerificationCode === ''){
        return res.ErrorFun('请输入验证码!') 
    }
    
    // 判断QQ邮箱验证码是否匹配
    if(myNewInfo.verificationCode !== myNewInfo.myVerificationCode){
        return res.ErrorFun('验证码错误!')
    }
    
    // 手机号正则
    let reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    if(!reg_tel.test(myNewInfo.phoneNumber)){
        return res.ErrorFun('请填写正确的手机号格式!')
    }
    
    // 是否存在空格正则
    let spase = /\s/g
    if(spase.test(myNewInfo.password) || spase.test(myNewInfo.newPassword)){
        return res.ErrorFun('密码不能存在空格!')
    }
    
    // 两次密码是否一致
    if(myNewInfo.password !== myNewInfo.newPassword){
        return res.ErrorFun('两次密码不一致!') 
    }

    // 注册SQL
    const registerNewUserSql = 'insert into personalinformation(phoneNumber, password, university, nickname, sex, QQMail) value (?, ?, ?, ?, ?, ?)'

    // 查询该手机号是否存在SQL
    const selectPhoneNumber = 'select * from personalinformation where phoneNumber = ?'

    // 查询QQ邮箱是否存在SQL
    const selectQQMail = 'select * from personalinformation where QQMail = ?'

    // 查询该手机号是否存在
    dataBase.query(selectPhoneNumber, myNewInfo.phoneNumber, (err, results) => {
        if(err){
           return res.ErrorFun('未知错误!请稍候再试！')
        }

        if(results.length > 0){
            return res.ErrorFun('该手机号已被使用！')
        }

        // 查询QQ邮箱是否存在
        dataBase.query(selectQQMail, myNewInfo.QQMail, (err, results) => {
            if(err){
            return res.ErrorFun('未知错误!请稍候再试！')
            }

            if(results.length > 0){
                return res.ErrorFun('该QQ邮箱已被绑定！')
            }

            // 注册
            dataBase.query(registerNewUserSql, [myNewInfo.phoneNumber, myNewInfo.password, myNewInfo.university, myNewInfo.nickname, myNewInfo.sex, myNewInfo.QQMail], (err, results) => {
                if(err){
                    return res.ErrorFun('未知错误!请稍候再试！')
                }

                if(results.affectedRows !== 1){
                    return res.ErrorFun('注册失败！')
                }

                res.send({
                    status: 200,
                    message: '注册成功！'
                })
            })
        })
    })
}

// 登入
function login(req, res){

    const selectUserStatusSql = 'select status from personalinformation where phoneNumber = ? || QQMail = ?'

    dataBase.query(selectUserStatusSql, [req.body.sccountNumber, req.body.sccountNumber], (err, results) => {
        if(err){
            return res.ErrorFun('未知错误！稍后重试！')
        }

        if(results[0].status === '1'){
            return res.ErrorFun('该账号被加入黑名单，无法使用！')
        }

        const selectUserSql = 'select * from personalinformation where phoneNumber = ? || QQMail = ?'

        dataBase.query(selectUserSql, [req.body.sccountNumber, req.body.sccountNumber], (err, results) => {
    
            if(err){
                return res.ErrorFun(err.message)
            }
    
            // 判断账户是否存在
            if(results.length <= 0){
                return res.ErrorFun('账号不存在！')
            }
    
            // 判断 密码 是否正确
            if(results[0].password !== req.body.password){
                return res.ErrorFun('密码错误！')
            }
    
            // 调用 jsonwebtoken.sign()生成JWT字符串，三个参数分别是: 参数1：用户信息对象、 参数2：加密密钥、 参数3：配置对象【可以配置当前 Token 的有效期】
            // const tokenStr = jsonwebtoken.sign({username: req.body.sccountNumber}, config.secretKey, { expiresIn: config.expiresInTime })
            const tokenStr = jsonwebtoken.sign({username: req.body.sccountNumber}, config.secretKey)
    
            res.send({
                status: 200,
                message: '登入成功!',
                token: tokenStr,
            })
        })

    })
}


// 获取分类列表信息
function getClassifiedList(req, res){

    const getClassifiedListSql = 'select * from classifiedlist'

    dataBase.query(getClassifiedListSql, (err, results) => {

        if(err){
            return res.ErrorFun('未知错误！请稍后重试！')
        }
        res.send({
            status: 200,
            message: '获取成功',
            classifiedList: results
        })

    })
}

// 获取通知信息
function getNotificationInformation(req, res){
    const getNotificationInformationSql = 'select text from notificationinformation'

    dataBase.query(getNotificationInformationSql, (err, results) => {
        if(err){
            return res.ErrorFun('未知错误！请稍后重试！')
        }
        res.send({
            status: 200,
            message: '获取成功',
            notificationInformation: results[0].text
        })
    })
}



module.exports = {
    registerNewUser,
    login,
    getClassifiedList,
    getNotificationInformation
}